package com.run_java_test.t.test_run;

import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Component
public class DynamicControllerRegistry {

    private final BeanDefinitionRegistry beanDefinitionRegistry;

    public DynamicControllerRegistry(ApplicationContext applicationContext) {
        this.beanDefinitionRegistry = (BeanDefinitionRegistry) applicationContext.getAutowireCapableBeanFactory();
    }

    /**
     * 动态注册 Controller
     *
     * @param beanName        Controller 的名称
     * @param controllerClass Controller 的 Class
     */
    public void registerController(String beanName, Class<?> controllerClass) {
        if (!beanDefinitionRegistry.containsBeanDefinition(beanName)) {
            BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(controllerClass);
            beanDefinitionRegistry.registerBeanDefinition(beanName, builder.getBeanDefinition());
        }
    }
}